const fs = require('fs');
const request = require('request');
const eachLimit = require('async/eachLimit');
// path模块，可以生产相对和绝对路径
const path = require('path');
const squel = require('squel');
const mysqlUtil = require('../utils/mysql_util');
const logUtil = require('../utils/log_util');
const download = require('../utils/downloadByUrl');



const sleep = (numberMillis) => {
  let now = new Date();
  const exitTime = now.getTime() + numberMillis;
  while (true) {
    now = new Date();
    if (now.getTime() > exitTime) {
      return;
    }
  }
};

/**
 * 通过文件名提取DesignId，并保存到数据库中
 */
const saveDesignId = filename => new Promise((res, rej) => {
  const designId = filename.substr(0, filename.indexOf('_'));
  const delSqlstr = squel.delete().from('designid').where('designId= ?', designId)
    .toString();
  const insertSql = squel.insert().into('designid').set('designId', designId)
    .toString();
  mysqlUtil.execute(delSqlstr)
    .then(() => {
      mysqlUtil.execute(insertSql)
        .then(() => {
          res(designId);
        })
        .catch((err) => {
          rej(err);
        });
    })
    .catch((err) => {
      rej(err);
    });
});

/**
 *  分析户型元数据（网络爬虫生产），并导入数据库
 * @param filePath
 * @returns {*}
 */
const importProjectMetaData = dataPath => new Promise((res, rej) => {
  // const dataPath1 = dataPath;
  fs.readdir(dataPath, (err, files) => {
    if (err) {
      logUtil.error(err);
      rej(err);
    }

    eachLimit(files, 1, ((filename, callback) => {
      const filePath = path.join(dataPath, filename);
      fs.stat(filePath, (err1, stats) => {
        if (err1) {
          rej(err1);
        }
        if (stats.isFile()) { // 是文件
          if (path.extname(filePath) === '.json') {
            const strFilePath = filePath.toString();
            const cc = 'E:\\03数据转移\\户型数据20171020\\soufang\\soufang\\';
            let areaName = strFilePath.substr(cc.length);
            areaName = areaName.substr(0, areaName.indexOf('\\'));
            const data = fs.readFileSync(filePath, 'utf-8');
            const info = JSON.parse(data);
            const param = {};
            param.strkey = info.key.replace('－', '-');
            param.name = info.name;
            param.areaName1 = areaName;
            param.data = data;

            if (info.area) {
              param.area = parseFloat(`0${info.area}`);
            }
            if (info.address) {
              param.address = info.address;
              if (info.address.indexOf(']') > 0) {
                param.address = info.address.substr(info.address.indexOf(']') + 1);
                param.areaName2 = info.address.substr(1, info.address.indexOf(']') - 1);
              }
            }
            if (info.name) {
              // "华夏厅天璟室湾10室6厅8卫".match(/\D+/g) 匹配文字
              param.neighbor = info.name.match(/\D+/g)[0];
              // "华夏天璟湾10室6厅8卫".match(/\d+室/g) 匹配数字
              if (info.name.indexOf('室') > 0) {
                param.bedrooms = parseInt(`0${info.name.match(/\d+室/g)}`, 10);
              }
              if (info.name.indexOf('厅') > 0) {
                param.living_rooms = parseInt(`0${info.name.match(/\d+厅/g)}`, 10);
              }
              if (info.name.indexOf('卫') > 0) {
                param.restrooms = parseInt(`0${info.name.match(/\d+卫/g)}`, 10);
              }
            }
            param.description = info.address;
            const sql = squel.insert().into('jmyd_tool.shoufang').setFields(param).toString();
            mysqlUtil.execute(sql)
              .then(() => {
                // logUtil.info(sql);
                // res(info.key);
                callback();
              })
              .catch((err4) => {
                rej(err4);
              });
          } else {
            callback();
          }
        } else {
          importProjectMetaData(filePath);
          callback();
        }
      });
    }), ((err1) => {
      if (err1) {
        console.log(err1);
        rej(err1);
      } else {
        res();
      }
    }));
  });
});

/**
 * 导入户型、方案数据
 * @param filePath
 * @returns {*}
 */
const importProject = dataPath => new Promise((res, rej) => {
  fs.readdir(dataPath, (err, files) => {
    if (err) {
      console.log(err);
      return;
    }
    // 异步，一次执行一个
    eachLimit(files, 1, (filename, callback) => {
      const filePath = path.join(dataPath, filename);
      fs.stat(filePath, (err1, stats) => {
        if (err1) rej(err1);
        if (stats.isFile()) { // 是文件
          if (path.extname(filePath) === '.json') {
            const fileData = fs.readFileSync(filePath, 'utf-8');
            try {
              const info = JSON.parse(fileData);
              info.name = info.name.replace('－', '-');
              const mysql = squel.select().from('jmyd_tool.apartment1')
                .field('strkey,id,name,area,address,bedrooms,living_rooms,restrooms,' +
                  'province,province_code,city,city_code,district ,district_code,' +
                  'areaName1,areaName2,neighbor,description')
                .where('strkey=?', info.name)
                .toString();
              mysqlUtil.execute(mysql)
                .then((data) => {
                  info.userLogin = 'jmyd';
                  info.vendorCode = '111';
                  info.assetType = 4;
                  info.userId = 1;


                  info.data.thumbnail3d = '';
                  if (data.length > 0) {
                    const param = data[0];
                    info.name = param.name;
                    info.sourceId = param.strkey;
                    info.description = param.description;
                    info.area = param.area;
                    info.realArea = param.area;
                    info.bedrooms = param.bedrooms;
                    info.livingRooms = param.living_rooms;
                    info.restrooms = param.restrooms;
                    info.province = { code: param.province_code, text: param.province };
                    info.city = { code: param.city_code, text: param.city };
                    info.district = { code: param.district_code, text: param.district };
                    info.neighbor = param.neighbor;
                    info.data.totalarea = param.area;
                  }
                  request.post('http://localhost:20091/project/save', { form: info });
                  sleep(50);
                  fs.unlinkSync(filePath);
                  logUtil.info(info.name);
                  // res(info.name);
                  callback();
                })
                .catch((err2) => {
                  rej(err2);
                });
            } catch (err3) {
              rej(err3);
            }
          } else {
            callback();
          }
        } else {
          importProject(filePath);
          callback();
        }
      });
    }, ((err1) => {
      if (err1) {
        console.log(err1);
      } else {
        res();
      }
    }));
  });
});


/**
 * 导入户型数据
 * @param filePath
 * @returns {*}
 */
const importHomeInfoByFile = dataPath => new Promise((res, rej) => {
  fs.readdir(dataPath, (err, files) => {
    if (err) {
      console.log(err);
      return;
    }
    // 异步，一次执行一个
    eachLimit(files, 10, (filename, callback) => {
      const filePath = path.join(dataPath, filename);

      fs.stat(filePath, (err1, stats) => {
        if (err1) rej(err1);
        try {
          if (stats && stats.isFile()) { // 是文件
            if (path.extname(filePath) === '.json') {
              // logUtil.info("json:"+filePath);
              const fileData = fs.readFileSync(filePath, 'utf-8');

              const info = JSON.parse(fileData);
              const free = JSON.parse(info.free[0]);
              const homeInfo = {};
              homeInfo.designId = filename.split('.')[0];
              // homeInfo.name = `${homeInfo.designId}_1220`;
              homeInfo.description = '20180108';
              const names = info.name.split(' ');
              if (names && names.length > 1) { homeInfo.name = names[1].concat((names.length > 2) ? names[2] : ""); } else { homeInfo.name = info.name; }
              homeInfo.data = { data: info.data.data, totalarea: free.grossArea };
              homeInfo.userLogin = 'jmyd';
              homeInfo.vendorCode = '111';
              homeInfo.assetType = 4;
              homeInfo.userId = 1;
              homeInfo.area = free.grossArea;
              if (free.area) {
                homeInfo.realArea = free.area.toFixed(2);
              }
              homeInfo.bedrooms = free.bedroomNum;
              homeInfo.livingRooms = free.livingroomNum;
              homeInfo.restrooms = free.bathroomNum;
              if (free.style) {
                homeInfo.style = free.style.name;
              }
              homeInfo.province = { code: `${free.province.id}000`, text: free.province.name };
              homeInfo.city = { code: `${free.city.id}000`, text: free.city.name };
              homeInfo.district = { code: `${free.district.id}000`, text: free.district.name };
              homeInfo.neighbor = free.neighbor;
              const temFilepath = filePath;

              request.post({ url: 'http://localhost:40091/project/save', form: homeInfo }, (err, httpResponse, body) => {
                if (err) {
                  logUtil.info(err);
                  setImmediate(callback);
                } else {
                  fs.unlink(temFilepath, (err) => {
                    if (err) logUtil.error(e);
                    logUtil.info(info.name);
                    setImmediate(callback);
                  });
                }
              });
            } else {
              logUtil.info(`not json:${filePath}`);
              setImmediate(callback);
            }
          } else {
            logUtil.info(`not file:${filePath}`);
            // importHomeInfoByFile(filePath);
            setImmediate(callback);
          }
        } catch (err3) {
          // rej(err3);
          logUtil.info(`error:${filePath}`);
          setImmediate(callback);
        }
      });
    }, ((err1) => {
      if (err1) {
        console.log(err1);
      } else {
        res();
      }
    }));
  });
});


/**
 * 导入户型、方案数据
 * @type {Async | *}
 */
exports.importProjectByFile = async (ctx) => {
  const dataPath = 'E:\\03数据转移\\户型数据20171020\\newfloor20171108\\newfloor';
  try {
    await importProject(dataPath);
    ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};
/**
 * 导入设计家户型数据 2017-12-20
 * @param ctx
 * @returns {Promise.<void>}
 */
const startImport = () => {
  const dataPath = 'F:\\homedata20171226\\uploadfile\\uploadfile';
  try {
    importHomeInfoByFile(dataPath);
    // ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};

const  saveDesxxx=()=>{
  const fileData = fs.readFileSync("./src/res/project.json", 'utf-8');
    const info = JSON.parse(fileData);
  request.post({ url: 'http://localhost:40091/project/save', form: info }, (err, httpResponse, body) => {
    if (err) {
      logUtil.info(err);
      setImmediate(callback);
    } else {
      fs.unlink(temFilepath, (err) => {
        if (err) logUtil.error(e);
        logUtil.info(info.name);
        setImmediate(callback);
      });
    }
  });
}

saveDesxxx();

exports.downLoadImage = async (ctx) => {
  try {
    const url = 'http://resource.jimuyida.com/jmyd-tool-image/ff98d7e9-0af9-422d-a3bf-73a2a923802f_jt.jpg';
    const fileName = 'ff98d7e9-0af9-422d-a3bf-73a2a923802f_jt.jpg';
    const pathName = 'E:\\数据';
    await download.saveFileByRequest(url, fileName, pathName);
    ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};

exports.saveImage = async (ctx) => {
  try {
    const designMap = ctx.request.body;
    ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};


exports.importProjectByServer = async (ctx) => {
  try {
    await importProjectByServer();
    ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};

// create table importProject as SELECT designId from project WHERE asset_type=2 and `status`!=10
// jmyd_guest jmyd1234
const importProjectByServer = () => new Promise((res, rej) => {
  const mysql = squel.select().from('jmyd_tool.importProject')
    .field('designId').toString();
  mysqlUtil.execute(mysql).then((results) => {
    if (results && results.length > 0) {
          // results.forEach((result) => {
      eachLimit(results, 1, (result, callback) => {
        const designid = result.designId;
        request(`http://10.19.176.174:20091/project/open?d=${designid}`, (error, response, body) => {
          const data = JSON.parse(body).data;
          data.login = 'weiq';
          data.userId = 75;
          data.vendorCode = '00L';
          data.description = '外网数据 20171221';
          data.agencyId = '48';
          data.sharedBrand = '00L1,00L2'; // 去掉共享标识
          request(`http://10.19.176.174:20091/project/open?d=${designid}`, (error, response, body) => {});

          request.post('http://localhost:20091/project/save', { form: data });
          sleep(50);
          logUtil.info(data.name);
          callback();
        });
      },
        ((err1) => {
          if (err1) {
            console.log(err1);
          } else {
            res();
          }
        }));
    }
  })
    .catch((err) => {
      rej(err);
    });
});

exports.inputProjectMetaData = async (ctx) => {
  const dataPath = 'E:\\03数据转移\\户型数据20171020\\soufang\\soufang';
  try {
    await importProjectMetaData(dataPath);
    ctx.body = 'success';
  } catch (err) {
    throw err;
  }
};

